package com.vf.cloud.paas.app.master.api.scene.controller;

import javax.servlet.http.HttpServletRequest;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.vf.cloud.paas.app.master.api.file.service.IThumbnail;
import com.vf.cloud.paas.app.master.common.domain.Scene;
import com.vf.cloud.paas.app.master.common.domain.SceneOrder;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.app.master.common.repository.base.Thumbnail;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.security.annotation.TokenRequired;
import com.vf.cloud.paas.common.util.DateUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.UuidUtil;
import com.vf.cloud.paas.common.util.WebUtils;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/scene")
public class SceneController {

	@Autowired
	private IThumbnail thumbnailImpl;

	@RLog(value = "分页获取场景列表", type = "user")
	@TokenRequired
	@GetMapping(value = { "/pages" }, produces = "application/json; charset=utf-8")
	public R<Page<Scene>> pages(HttpServletRequest request,
			@RequestParam(name = "classifyId", required = false, defaultValue = "") String classifyId,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		User user = WebUtils.getCurUser(request);
		if (user == null) {
			return R.expired();
		}
		String sqlExceptSelect = " from " + Scene.TABLE_NAME + "  a WHERE a.classify_id='" + classifyId + "' ";
		if (StrKit.equals("admin", user.getRoleMark())) {
		} else if (StrKit.equals("group", user.getRoleMark())) {
			sqlExceptSelect += " and ( a.create_user_id ='" + user.getId()
					+ "' or ( a.create_user_id in ( select id from  master_user where pid='" + user.getId() + "' )) "
					+ " or (a.status='1' and a.create_user_id!='" + user.getId()
					+ "' and a.create_user_id not in (select id from  master_user where pid='" + user.getId()
					+ "')   )          ) ";
		} else {
			sqlExceptSelect += " and ( a.create_user_id ='" + user.getId()
					+ "'  or (a.status='1' and  a.create_user_id!='" + user.getId() + "') ) ";
		}
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " and name like '%" + keywords + "%' ";
		}
		sqlExceptSelect += "  ORDER BY   a.modify_time desc ";
		return R.ok(Scene.dao.paginate(cur, limit, "select * ", sqlExceptSelect));
	}

	@RLog(value = "保村场景", type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Scene> save(HttpServletRequest request, MultipartFile thumbnailFile, Scene scene) {
		User user = WebUtils.getCurUser(request);
		try {
			Thumbnail thumbnailEntity = null;
			if (thumbnailFile != null) {
				thumbnailEntity = new Thumbnail();
				thumbnailEntity.setSize(thumbnailFile.getSize());
				thumbnailEntity.setName(scene.getName());
				thumbnailEntity.setContent(new Binary(thumbnailFile.getBytes()));
			}

			if (StrKit.notBlank(scene.getId())) {
				scene.setModifyUserId(user.getId());
				if (scene.update()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(scene.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}
					return R.ok(scene);
				} else {
					return R.failed();
				}
			} else {
				scene.setId(UuidUtil.getUUID());
				scene.setCreateUserId(user.getPid());

				SceneOrder sceneOrder = new SceneOrder();
				sceneOrder.setId(scene.getId());
				sceneOrder.setMasterId(user.getPid());
				sceneOrder.save();
				if (scene.save()) {
					if (thumbnailEntity != null) {
						try {
							thumbnailEntity.setId(scene.getId());
							thumbnailImpl.save(thumbnailEntity);
						} catch (Exception e) {
						}
					}
					return R.ok(scene);
				} else {
					return R.failed();
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RLog(value = "删除场景", type = "user")
	@TokenRequired
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public R<String> delete(HttpServletRequest request, @RequestBody Scene scene) {
		if (scene == null) {
			return R.failed("参数必填.");
		}
		if (Scene.dao.deleteById(scene.getId())) {
			thumbnailImpl.deleteById(scene.getId());
			SceneOrder.dao.deleteById(scene.getId());
			return R.ok();
		}
		return R.failed();
	}

	@RLog(value = "复制场景", type = "user")
	@TokenRequired
	@RequestMapping(value = "/copy", method = RequestMethod.POST)
	public R<String> copy(HttpServletRequest request, @RequestBody Scene param) {
		if (param == null) {
			return R.failed("参数必填.");
		}

		Scene scene = Scene.dao.findById(param.getId());
		if (scene == null) {
			return R.failed("场景不存在.");
		}

		User user = WebUtils.getCurUser(request);
		if (user == null) {
			return R.expired();
		}

		scene.setId(UuidUtil.getUUID());
		scene.setName(scene.getName() + "-Copy");
		scene.setCreateUserId(user.getCreateUserId());
		scene.setCreateTime(DateUtil.getLocalDateTime());
		if (scene.save()) {
			Thumbnail thumbnail = thumbnailImpl.findById(param.getId());
			if (thumbnail != null) {
				thumbnail.setId(scene.getId());
				thumbnailImpl.save(thumbnail);
			}
			return R.ok();
		}
		return R.failed();
	}

}
